package com.sumer.juc;

/**
 * 线程通信
 */
public class ThreadA {

    public static void main(String[] args) {
        Data data = new Data();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.increment();
            }
        },"A").start();
        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                data.decrement();
            }
        },"B").start();
    }

}

class Data {

    private int number;

    public synchronized void increment() {
        if (number != 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number++;
        this.notify();
        System.out.println(Thread.currentThread().getName() + " ---> " + number);
    }

    public synchronized void decrement() {
        if (number == 0) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        number--;
        this.notify();
        System.out.println(Thread.currentThread().getName() + " ---> " + number);
    }
}
